package com.topcent.tioxyc.xxljob;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.SalesOrder;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/3/17 10:52
 * @Description: 销售报表读取本月之前最新金额数据
 */
@Slf4j
@Component
public class SaleDataAddSqlXxlJob {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @XxlJob("saleDataAddSql")
    public String saleDataAddSql() {
        List<SalesOrder> orderList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        // 销售订单流程：667230b322a8581756b78353
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            orderList.addAll(list);
        } while (fale);
        // 过滤数据
        List<SalesOrder> salesOrderList = processOrders(orderList);
        // 清空原表的数据
        yy1KpiMapper.truncateTableOfSaleOrder001();
        // 插入数据
        salesOrderList.forEach(salesOrder -> {
            salesOrder.set_widget_1718759603984(salesOrder.get_widget_1718759603987() * salesOrder.get_widget_1718759603984());
            yy1KpiMapper.insertSaleOrder001(salesOrder);
        });
        return "处理数据大小===》》》 " + salesOrderList.size();
    }

    public static List<SalesOrder> processOrders(List<SalesOrder> orders) {
        LocalDateTime now = LocalDateTime.now();

        // 过滤掉本月的数据
        List<SalesOrder> filteredOrders = orders.stream()
                .filter(order -> {
                    LocalDateTime reviewDate = order.getReview_date().toLocalDateTime();
                    return reviewDate.getYear() != now.getYear() ||
                            reviewDate.getMonthValue() != now.getMonthValue();
                })
                .toList();

        // 按销售订单号分组，获取每组中最新的数据，并设置最小时间
        return filteredOrders.stream()
                .collect(Collectors.groupingBy(SalesOrder::get_widget_1718759603973))
                .values().stream()
                .map(group -> {
                    // 获取最大日期的订单
                    SalesOrder maxOrder = Collections.max(group, Comparator.comparing(SalesOrder::getReview_date));

                    // 获取最小日期
                    if (group.size() >= 2) { // 仅当分组有2条以上数据时设置最小时间
                        SalesOrder minOrder = Collections.min(group, Comparator.comparing(SalesOrder::getReview_date));
                        maxOrder.setMin_time(minOrder.getReview_date()); // 设置最小时间
                    }

                    return maxOrder;
                })
                .collect(Collectors.toList());
    }

}
